#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtGui>
#include  "dialog.h"
#include  "about.h"
#include  "dialogfind.h"
#include  "dialogconvert.h"
#include  "dialogupdat.h"
#include  "dialogfavo.h"
#ifdef   Q_WS_WIN
#include  "dialogmdb.h"
#endif
#include  "dialoggoto.h"
#include  "dialogoption.h"
#include  "mdbexport.h"
#include  "print.h"

//تحميل البرنامج
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindowClass)
{
    ui->setupUi(this);
    Messages = new messages();
    Findbook=new findbook();
    DataBook=new databook();
#if QT_VERSION >= 0x040600
   view= new View(this);
#endif

    m_pathUser=QDir::homePath()+"/.kirtasse";
    m_pathApp=QApplication::applicationDirPath();
    m_currentBookIndex=0;
    for(int r=0;r<10;++r)
    {
        m_isTefsir[r]=false;
        m_treeFahrass_modified[r]=false;
        m_book_modified[r]=false;
        m_toolEditFahrass[r]=false;
    }
    m_treeGroup_modified=false;
   
   

    ui->frame_anim->setVisible(false);
    ui->lineEdit->setVisible(false);
    m_listTab.append("0");
    m_find_tree_book=true;
    m_txtBrowser = ui->tabWidget->currentWidget()->findChild<QTextBrowser *>();


    //**********************عمليات التحميل*******
    updateIconEndAction();
    tabCreatFahrass();
on_actionPageIntro_triggered();                              //تحميل ملف السمة وبيانات الطول و العرض ووو
    charge_groupe();                                       //تحميل شجرة الكتب
    Messages->treeChargeJozaa(ui->treeWidget_curaan);       //تحميل اجزاء القرءان
    Messages->recentCharge();               //تحميل قائمة الكتب السابقة

    Messages->favorite_charge(ui->treeWidget_fav,m_icondir,m_icondfile);

    loadLayout();

}
//عند خروج البرنامج
MainWindow::~MainWindow()
{
 Messages->recentSave(); //حفظ الكتب السابقة
    Savelayou();
    Messages->favorite_save(ui->treeWidget_fav);
    delete ui;
}
void MainWindow::closeEvent(QCloseEvent *e)
{
    Findbook ->stopFind=true;
    if (m_treeGroup_modified==true){
        int reponse = QMessageBox::warning(this, trUtf8("تنبيه"), trUtf8("هل تريد حفظ التغييرات المدخلة على مجموعة الكتب ") ,QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        if (reponse == QMessageBox::Save){
            if ( Messages->treeSaveGroupe(ui->treeWidget_books)){
                QMessageBox::information(this,trUtf8("معلومات"), trUtf8("تمت عملية حفظ مجموعة الكتب بنجاح"));
                m_treeGroup_modified=false;                
            }
        }else if (reponse == QMessageBox::Cancel){
            e->ignore();
            return;
        }
    }

    int  tabcount=ui->tabWidget->count();
    //حفظ السمة والبيانات عند الخروج
    for(int r=0;r<tabcount;++r)
    {

        QTextBrowser *txtBrowser = ui->tabWidget->widget(r)->findChild<QTextBrowser *>();
        QString name=txtBrowser->objectName();
        QString  str = name.section('_', -1);
        QVariant indx=str;

        if (!m_BookName[indx.toInt()].isEmpty()){                              //حفظ قائمة الكتب السابقة


            if(txtBrowser->document()->isModified()){
                DataBook->boocNumIndex=indx.toInt();
                DataBook->updatPage("",txtBrowser->document()->toPlainText(),true);
                m_book_modified[indx.toInt()]=true;
            }
            if (closeMessages(m_BookTitle[indx.toInt()],indx.toInt())==false){
                e->ignore();
                return;
            }

            QVariant idbk=DataBook->currentPosition[indx.toInt()];
            Messages->recentChange(m_BookName[indx.toInt()],m_BookTitle[indx.toInt()],m_BookAuthor[indx.toInt()],idbk.toString(),m_recentNbr,m_isTefsir[indx.toInt()]);


        }
    }

    e->accept();


}
bool MainWindow::closeMessages(QString title,int index)
{
    if (m_treeFahrass_modified[index]==true){
        int reponse = QMessageBox::warning(this, trUtf8("تنبيه"), trUtf8("هل تريد حفظ فهرسة : ") +title, QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        if (reponse == QMessageBox::Save){
            saveFahrass(index);


        }else if (reponse == QMessageBox::Cancel){

            return false;
        }
    }
    if (m_book_modified[index]==true){
        int reponse = QMessageBox::warning(this, trUtf8("تنبيه"), trUtf8("هل تريد حفظ التغييرات على كتاب : ")+title+ " ؟" , QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        if (reponse == QMessageBox::Save){
        saveCurrentBook(index);

        }else if (reponse == QMessageBox::Cancel){
            return false;
        }
    }
    return true;
}

void MainWindow::updateIconEndAction()
{
    //*******************menu tool**************
    ui->menuDockTooBar->addAction(ui->dockWidget_books->toggleViewAction());
    ui->dockWidget_books->toggleViewAction()->setShortcut(QKeySequence(tr("Ctrl+Shift+b")));
    ui->menuDockTooBar->addAction(ui->dockWidget_curaan->toggleViewAction());
    ui->dockWidget_curaan->toggleViewAction()->setShortcut(QKeySequence(tr("Ctrl+Shift+c")));
    ui->menuDockTooBar->addAction(ui->dockWidget_fahras->toggleViewAction());
    ui->dockWidget_fahras->toggleViewAction()->setShortcut(QKeySequence(tr("Ctrl+Shift+l")));
    ui->menuDockTooBar->addAction(ui->dockWidget_favorite->toggleViewAction());
    ui->dockWidget_favorite->toggleViewAction()->setShortcut(QKeySequence(tr("Ctrl+Shift+v")));
    ui->menuDockTooBar->addAction(ui->dockWidget_find->toggleViewAction());
    ui->dockWidget_find->toggleViewAction()->setShortcut(QKeySequence(tr("Ctrl+Shift+f")));
    ui->menuDockTooBar->addSeparator();
    ui->menuDockTooBar->addAction(ui->mainToolBar->toggleViewAction());
    ui->mainToolBar->toggleViewAction()->setShortcut(QKeySequence(tr("Ctrl+Shift+t")));
    ui->menuDockTooBar->addAction(ui->toolBar_navegator->toggleViewAction());
    ui->toolBar_navegator->toggleViewAction()->setShortcut(QKeySequence(tr("Ctrl+Shift+n")));

    //*******************icons**************


    m_icondir=style()->standardIcon(QStyle::SP_DirIcon);
    m_icondfile=style()->standardIcon(QStyle::SP_FileIcon);
    m_iconGroup.addPixmap(QPixmap(QString::fromUtf8(":/images/image/groupb.png")), QIcon::Normal, QIcon::Off);
    QIcon iconRen;
    iconRen.addPixmap(QPixmap(QString::fromUtf8(":/images/image/edit-rename.png")), QIcon::Normal, QIcon::Off);
    m_iconbook.addPixmap(QPixmap(QString::fromUtf8(":/images/image/FIN_book.png")), QIcon::Normal, QIcon::Off);
    m_iconaut.addPixmap(QPixmap(QString::fromUtf8(":/images/image/edit-find-user.png")), QIcon::Normal, QIcon::Off);

    QIcon iconsave;
    iconsave.addPixmap(QPixmap(QString::fromUtf8(":/images/image/document-save.png")), QIcon::Normal, QIcon::Off);
    QIcon iconGo;
    iconGo.addPixmap(QPixmap(QString::fromUtf8(":/images/image/arrow-left.png")), QIcon::Normal, QIcon::Off);
    QIcon iconundoback;
    iconundoback.addPixmap(QPixmap(QString::fromUtf8(":/images/image/undo-back.png")), QIcon::Normal, QIcon::Off);
    QIcon iconundonext;
    iconundonext.addPixmap(QPixmap(QString::fromUtf8(":/images/image/undo-next.png")), QIcon::Normal, QIcon::Off);
    //********انشاء شجرة البحوث*************
    {
        connect(ui->treeWidgetFind, SIGNAL(itemActivated(QTreeWidgetItem* ,int)), this, SLOT(showResultFind(QTreeWidgetItem* )));
        ui->treeWidget_books->setColumnHidden(2,true);
        ui->treeWidget_books->setColumnWidth(0,200);
        ui->treeWidget_books->header()->setVisible(true);
        ui->  treeWidget_fav->setColumnWidth(0,300);
        ui->treeWidget_fav->header()->setVisible(true);
    }
    //******اضافات الى شريط المعلومات*******
    {
        m_label_progress=new QLabel;
        ui->statusBar->addWidget(m_label_progress);
        m_progressFind=new QProgressBar();
        m_label_progressImg=new QLabel;
        ui->statusBar->addWidget(m_label_progressImg);
        ui->statusBar->addWidget(m_progressFind);
        BtnStopFind=new QPushButton(style()->standardIcon(QStyle::SP_MediaStop), "", this);
        BtnStopFind->setFlat(true);
        BtnStopFind->setMaximumWidth(25);
        ui->statusBar->addWidget(BtnStopFind);
        connect(BtnStopFind, SIGNAL(clicked()), this, SLOT(search_stop()));
        m_label_progress_info=new QLabel;
        ui->statusBar->addWidget(m_label_progress_info);
        m_label_progress->setVisible(false);
        m_label_progressImg->setVisible(false);
        BtnStopFind->setVisible(false);
        m_progressFind->setVisible(false);
        ui->frameEdit->setVisible(false);

    }
      ui->pushButtonEditClose->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton));
    //************favotite المفضلة**********
    {

QLineEdit *lineEditFindFavo = new QLineEdit(this);
lineEditFindFavo->setMaximumWidth(200);

connect(lineEditFindFavo, SIGNAL(textChanged(QString)), this, SLOT(find_favo_textChanged(QString)));
ui->toolBarFavo->insertWidget(ui->actionFavSave,lineEditFindFavo);
ui->toolBarFavo->insertSeparator(ui->actionFavSave);
        ui->actionFavItemDown->setIcon(style()->standardIcon(QStyle::SP_ArrowDown));
        ui->actionFavItemUp->setIcon(style()->standardIcon(QStyle::SP_ArrowUp));
        ui->horizontalLayoutFavo->addWidget(ui->toolBarFavo);
    }
      ui->actionFindItemDown->setIcon(style()->standardIcon(QStyle::SP_ArrowDown));
      ui->actionFindItemUp->setIcon(style()->standardIcon(QStyle::SP_ArrowUp));
       ui->actionFindLoad->setIcon(style()->standardIcon(QStyle::SP_DirOpenIcon));
      labelTextFind=new QLabel();
      ui->toolBarFind->insertWidget(ui->actionFindItemUp,labelTextFind);
       ui->toolBarFind->insertSeparator(ui->actionFindItemUp);
     ui->  horizontalLayoutFind->addWidget(ui->toolBarFind);


    //********اضافة القوائم menu************
    {
        AC_openBookInNewTab=new QAction(style()->standardIcon(QStyle::SP_FileDialogNewFolder),trUtf8("فتح في لسان جديد"), this);
        AC_open_book = new QAction(style()->standardIcon(QStyle::SP_DirOpenIcon),trUtf8("فتح الكتاب المحدد"), this);
        AC_remove_book = new QAction(style()->standardIcon(QStyle::SP_DialogCancelButton),trUtf8("حذف الكتاب المحدد"), this);
        AC_updat_book= new QAction(trUtf8("تحرير بيانات الكتاب المحدد"), this);
        AC_path_book= new QAction(trUtf8("مسار الكتاب المحدد"), this);
        //***********groupe menu************************************************
        AC_remove_groupe = new QAction(style()->standardIcon(QStyle::SP_DialogCancelButton),trUtf8("حذف العنصر المحدد"), this);
        AC_add_groupe = new QAction(style()->standardIcon(QStyle::SP_FileDialogNewFolder),trUtf8("إظافة مجموعةالى القسم المحدد"), this);
        AC_add_categorie = new QAction(style()->standardIcon(QStyle::SP_FileDialogNewFolder),trUtf8("إظافة قسم جديد"), this);

        AC_rename_groupe= new QAction(iconRen,trUtf8("اعادة تسمية العنصر المحدد"), this);
        //*******************اضافة قائمة زرالبحث عن كتاب او مؤلف*********************



    }
    //****اضافات الى شريط الادوات toolbar****
    {

labelAnim=new QLabel(ui->toolBarAnim);
labelAnim->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
ui->toolBarAnim->addSeparator();
 ui->toolBarAnim->addWidget(labelAnim);

 ui->frame_5->layout()->addWidget(ui->toolBarAnim);
        m_lineEditSearchInDoc=new QLineEdit(this);
        AC_go_search_indoc=new QAction(iconGo,trUtf8("البحث في الصفحة"), this);
        AC_go_search_incurbook=new QAction(m_iconbook,trUtf8("البحث في الكتاب الحالي"), this);
        ui->mainToolBar->addWidget(m_lineEditSearchInDoc);
        ui->mainToolBar->addAction(AC_go_search_indoc);
        ui->mainToolBar->addSeparator();
        ui->mainToolBar->addAction(AC_go_search_incurbook);
        m_label_page = new QLabel("");
        ui->toolBar_navegator->addWidget(m_label_page);


        AC_nextHistorie= new QAction(iconundonext,trUtf8("التنقل التالي"), this);
        AC_prevHistorie=new QAction(iconundoback,trUtf8("التنقل السابق"), this);
        AC_prevHistorie->setEnabled(false);
        AC_nextHistorie->setEnabled(false);
        ui->toolBar_navegator->addAction(AC_prevHistorie);
        ui->toolBar_navegator->addAction(AC_nextHistorie);
    }
    //**القوائم المنسدلة للكتب السابقة combobox recent**
    {
for (int i = 0; i < MaxRecentFiles; ++i) {
                 recentFileActs[i] = new QAction(this);
                 recentFileActs[i]->setVisible(false);
                 connect(recentFileActs[i], SIGNAL(triggered()),
                         this, SLOT(openRecentFile()));
                 ui->menuRecent->addAction(recentFileActs[i]);

                 Messages->recentFileActs[i]=recentFileActs[i];

}
ui->mainToolBar->addSeparator();
ui->mainToolBar->addAction(ui->menuRecent->menuAction());




//        ui->toolBarrecent->addWidget(m_combo_recent);
//         ui->toolBarrecent->addAction(AC_go_recent);
//ui->horizontalLayoutRecent->addWidget(barRecent);
    }
    //***********الاشارات signal end slot****
    {
        connect(AC_open_book, SIGNAL(triggered()), this, SLOT(menuOpenBook()));
        connect(AC_openBookInNewTab, SIGNAL(triggered()), this, SLOT(tabOpenInNewTab()));
        connect(AC_remove_book, SIGNAL(triggered()), this, SLOT(menu_BookRemove()));
        connect(AC_updat_book, SIGNAL(triggered()), this, SLOT(menu_BookUpdat()));
        connect(AC_path_book, SIGNAL(triggered()), this, SLOT(menu_BookPath()));
        connect(AC_remove_groupe, SIGNAL(triggered()), this, SLOT(menu_GroupeRemove()));
        connect(AC_add_groupe, SIGNAL(triggered()), this, SLOT(menu_GroupeAdd()));
        connect(AC_add_categorie, SIGNAL(triggered()), this, SLOT(menu_CategorieAdd()));

        connect(AC_rename_groupe, SIGNAL(triggered()), this, SLOT(menu_GroupeRename()));


        connect(AC_go_search_indoc, SIGNAL(triggered()), this, SLOT(search_indoc()));
        connect(AC_go_search_incurbook, SIGNAL(triggered()), this, SLOT(find_in_curbook()));
        connect(m_lineEditSearchInDoc, SIGNAL(returnPressed()), this, SLOT(search_indoc()));


        connect(m_txtBrowser, SIGNAL(highlighted(const QUrl)), this, SLOT(highlighted(QUrl)));
        connect(m_txtBrowser, SIGNAL(anchorClicked(const QUrl)), this, SLOT(anchorClicked(QUrl)));

        connect(AC_nextHistorie, SIGNAL(triggered()), this, SLOT(historieNext ()));

        connect(AC_prevHistorie, SIGNAL(triggered()), this, SLOT(historiePrev()));
    }
    //***********************الممؤثرات الحركيةanimation*****************************
    {
        m_txtBetaka=new QLabel();
        m_txtBetaka->setLayoutDirection(Qt::RightToLeft);
        m_txtBetaka->setPixmap(QPixmap(QString::fromUtf8(":/images/image/groupbook.png")));
        m_scene.addWidget(m_txtBetaka);
        m_scene.setBackgroundBrush(m_txtBetaka->palette().base());
        m_txtBetaka->setBackgroundRole(QPalette::Base);


        ui->graphicsView->setScene(&m_scene);

        m_txtBetaka->setFixedWidth(400);
        m_txtBetaka->setFixedHeight(400);
        m_txtBetaka->setAlignment(Qt::AlignTop);
        m_txtBetaka->setAutoFillBackground(true);
        startAnimationBook();
#if QT_VERSION >= 0x040600
        view->treeView=ui->treeWidget_books;
//        view->comboBox=m_combo_recent;

        view->lineEdit=ui->lineEdit;
        view->label=labelAnim;
        view->chargePixmap();
        ui->horizontalLayout_7->addWidget(view);
#endif

    }
    //---------------------------عناصر تحرير الكتاب

    ui->horizontalLayout_5->addWidget(ui->toolBarEditBook);
ui->actionItemFahUp->setIcon(style()->standardIcon(QStyle::SP_ArrowUp));
ui->actionItemDown->setIcon(style()->standardIcon(QStyle::SP_ArrowDown));
    connect(ui->actionItemDown, SIGNAL(triggered()), this, SLOT(itemFahrasMoveDown()));
    connect(ui->actionItemFahUp, SIGNAL(triggered()), this, SLOT(itemFahrasMoveUp()));
    connect(ui->actionItemFahRen, SIGNAL(triggered()), this, SLOT(itemFahrasRename()));
    connect(ui->actionItemFahDelet, SIGNAL(triggered()), this, SLOT(itemFahrasRemove()));
    connect(ui->actionFahAddItem, SIGNAL(triggered()), this, SLOT( itemFahrasAdd()));
    connect(ui->actionFahAddChild, SIGNAL(triggered()), this, SLOT( itemFahrasAddChild()));
    connect(ui->actionSaveEdit, SIGNAL(triggered()), this, SLOT( saveBookEndFahras()));
    /////////////////عناصر شجرة الكتب

      QLineEdit *lineEditFind = new QLineEdit(this);
      findBkOrHtAction = new QAction(QPixmap(QString::fromUtf8(":/images/image/FIN_book.png")),trUtf8("بحث"), this);

ui->toolBarBooks->insertWidget(ui->actionFindBkOrHt,lineEditFind);
     ui->horizontalLayoutBook->addWidget(ui->toolBarBooks);

     connect(lineEditFind, SIGNAL(textChanged(QString)), this, SLOT(searchInTreebook(QString)));
     connect(ui->actionBookExpAll, SIGNAL(triggered()), ui->treeWidget_books, SLOT(expandAll()));
     connect(ui->actionBookColpAll, SIGNAL(triggered()), ui->treeWidget_books, SLOT(collapseAll()));
     connect(ui->actionFindBkOrHt, SIGNAL(triggered()), this, SLOT(find_bookOrHautor()));

     //--------------عناصر الفهرسة
     QToolBar *barFahras = new QToolBar;
      barFahras->setIconSize(QSize(18,18));
lineEditFindFah = new QLineEdit(this);
 expandTreeFah = new QAction(QPixmap(QString::fromUtf8(":/images/image/btnfolder.png")),trUtf8("توسيع الكل"), this);
 colapsTreeFah = new QAction(QPixmap(QString::fromUtf8(":/images/image/colapse.png")),trUtf8("غلق الكل"), this);
 barFahras->addWidget(lineEditFindFah);
 barFahras->addSeparator();
 barFahras->addAction(expandTreeFah);
 barFahras->addAction(colapsTreeFah);
 ui->horizontalLayoutFahras->addWidget(barFahras);

 //***********



 }

//open book****فتح الكتب*****************
void MainWindow:: open_dataBase(QString name,QString title,QString Autor,int position)       //فتح الكتاب
{ 
  
    //اذا كان نفس الكتاب مفتوحا
       int  tabcount=ui->tabWidget->count();
    for(int r=0;r<tabcount;++r){
        QTextBrowser *txtBrowser = ui->tabWidget->widget(r)->findChild<QTextBrowser *>();
        QString txtname=txtBrowser->objectName();
        QString  str = txtname.section('_', -1);
        QVariant indx=str;
        if (m_BookName[indx.toInt()]==name){

            ui->tabWidget->setCurrentIndex(r);
            return;
        }
    }
    //حفظ التغييرات اذا كان هناك تغيير
    if(m_txtBrowser->document()->isModified()){
        DataBook->updatPage("",m_txtBrowser->document()->toPlainText(),true);
        m_book_modified[m_currentBookIndex]=true;      
    }

    if (closeMessages(m_BookTitle[m_currentBookIndex],m_currentBookIndex)==false){

        return;
    }
    //التأكد من وجود الكتاب في المسار
    QString bkpath;           //مسار الكتاب    
    QFile file;
 if( file.exists( m_pathCostm + "/" + name +"/book.xml")){
    if (m_currentBookIndex==0){tabCreatTabNew();}
     bkpath=m_pathCostm + "/" + name +"/book.xml";
     m_currentBookPath[m_currentBookIndex]=m_pathCostm + "/" + name;
 }else if(file.exists( m_pathApp + "/books/" + name +"/book.xml")){
    if (m_currentBookIndex==0){tabCreatTabNew();}
     bkpath=m_pathApp + "/books/" + name +"/book.xml";
     m_currentBookPath[m_currentBookIndex]=m_pathApp + "/books/" + name;

 }else{
     QMessageBox::information(this,trUtf8("خطأ"),m_pathCostm + "/" + name +trUtf8( "غير موجود ") );
     return;
 }
    //***********************************
    file.close();

    m_listHistoriePrev[m_currentBookIndex].clear();
    m_listHistorieNext[m_currentBookIndex].clear();
    m_listHistoriePrev[m_currentBookIndex].append(position);
    AC_prevHistorie->setEnabled(false);
    AC_nextHistorie->setEnabled(false);
    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    //حفظ الكتاب السابق
    if (!m_BookName[m_currentBookIndex].isEmpty()){
        QVariant idbk=DataBook->currentPosition[DataBook->boocNumIndex];
        Messages->recentChange(m_BookName[m_currentBookIndex],m_BookTitle[m_currentBookIndex],m_BookAuthor[m_currentBookIndex],idbk.toString(),m_recentNbr,m_isTefsir[m_currentBookIndex]);
        Messages->recentCharge();

    }
    //فتح الكتاب
    if ( DataBook->openBook(name,position,bkpath)==true)
    {        

        m_BookName[m_currentBookIndex]=name;
        m_BookTitle[m_currentBookIndex]=title;
        m_BookAuthor[m_currentBookIndex]=Autor;
        bookValueChanged(position);
       m_isTefsir[m_currentBookIndex]=DataBook->isTefsir ;
    }else{
        QMessageBox::information(this,trUtf8("خطأ"),bkpath + trUtf8("التنسيق غير صحيح ") );
        QApplication::restoreOverrideCursor();     
        return;
    }
    //تحميل الشجرة الكتاب
Messages->treeChargeFahrass(m_treeFahras[m_currentBookIndex],m_currentBookPath[m_currentBookIndex]);
 //Messages->treeChargeFahrass(m_treeFahras[m_currentBookIndex],m_currentBookPath[m_currentBookIndex]);
    ui->dockWidget_fahras->setShown(true);
    m_treeFahras[m_currentBookIndex]->headerItem()->setText(0,m_BookTitle[m_currentBookIndex]);
    m_treeFahras[m_currentBookIndex]->setColumnCount(2);
    m_treeFahras[m_currentBookIndex]->setColumnHidden(1,true);
    //استعادة اصل المتغيرات
    m_book_modified[m_currentBookIndex]=false; 
    m_treeFahrass_modified[m_currentBookIndex]=false;
    ui->frameEdit->setVisible(false);
    m_txtBrowser->setReadOnly(true);
    m_txtBrowser->setUndoRedoEnabled(false);
    m_treeFahras[m_currentBookIndex]->setDragDropMode(QAbstractItemView::NoDragDrop);
    m_treeFahras[m_currentBookIndex]->setSelectionMode(QAbstractItemView::SingleSelection);
    m_toolEditFahrass[m_currentBookIndex]=false;
    ui->tabWidget->setTabText(ui->tabWidget->currentIndex(),m_BookTitle[m_currentBookIndex]);
    this->tabifyDockWidget(ui->dockWidget_books,ui->dockWidget_fahras);
    QApplication::restoreOverrideCursor();
}
void MainWindow::menuOpenBook()//النقر على قائمة فتح كتاب
{
    QTreeWidgetItem *item=ui->treeWidget_books->currentItem();
    if (!item->data(1,1).isNull()){
        open_dataBase(item->data(1,1).toString(),item->text(0),item->text(1),0);
    }
}

void MainWindow::on_pushButton_gotafsir_clicked()//فتح كتاب التفسير
{
    int index=ui->comboBox_tafasir->currentIndex();
    QVariant comboR_data=ui->comboBox_tafasir->itemData(index);
    QString myname = comboR_data.toString().section('/', 0, 0);
    QString myaut = comboR_data.toString().section('/', -1);
    if (!myname.isEmpty())
    {

        open_dataBase(myname,ui->comboBox_tafasir->currentText(),myaut,0);
         m_isTefsir[m_currentBookIndex]=true;
    }
}
void MainWindow::charge_groupe()//تحميل شجرة الكتب
{
    Messages->comboGroup=ui->comboBox_tafasir;
    Messages->treeChargeGroupe(ui->treeWidget_books,0,false);
}
void MainWindow::on_comboBox_currentIndexChanged(int index)//codexml souara  //فتح السور فتح الاجزاء
{
    ui->treeWidget_curaan->clear();
    if (index==0){
        Messages->treeChargeJozaa(ui->treeWidget_curaan);
    }else {
        Messages->treeChargeSoura(ui->treeWidget_curaan);
    }
}

//save load other************************************************************
void MainWindow::on_action_fulscreen_triggered()//ملأ الشاشة
{
    if (this->windowState()==Qt::WindowFullScreen){
        this->showNormal();
    } else {
        this->showFullScreen();
    }
}

void MainWindow::Savelayou()//حفظ البيانات الى ملف
{
    QSettings settings(m_pathUser+"/data/setting.ini",
                       QSettings::IniFormat);
    // QSettings settings("Kirtasse", "setting");
    settings.beginGroup("MainWindow");
    settings.setValue("style", m_MystyleName);
    settings.setValue("font",  m_txtBrowser->font().toString());
    settings.setValue("fontTitle", m_WebFontTitle);
    settings.setValue("bcolor",m_WebColorBack);
    settings.setValue("WebFontColor",m_WebFontColor);
    settings.setValue("WebFontFindColor",m_WebFontFindColor);
    settings.setValue("WebFontPrefertColor",m_WebFontPrefertColor);
    settings.setValue("WebFontTitleColor",m_WebFontTitleColor);
    settings.setValue("recentNbr",m_recentNbr);
    settings.setValue("pathCostm",m_pathCostm);
    settings.setValue("isThreeD",ui->actionTreeD->isChecked());
    settings.setValue("WebCadre",m_WebCadre);
    settings.setValue("geo_data", saveGeometry());
    settings.setValue("layout_data", saveState());
    settings.endGroup();
}

void MainWindow::loadLayout()//load layou
{

    QByteArray layo_data=QByteArray::fromHex("(000000ff00000000fd00000002000000010000010600000276fc0200000001fc0000004000000276000001330007"
                                             "fffffa000000020100000003fb000000220064006f0063006b005700690064006700650074005f0063007500720061006100"
                                             "6e0100000000ffffffff000000b600fffffffb000000220064006f0063006b005700690064006700650074005f00660061006"
                                             "80072006100730100000000ffffffff000000970007fffffb000000200064006f0063006b005700690064006700650074005f0"
                                             "062006f006f006b0073010000045200000106000000780000058c0000000300000558000000c7fc0100000001fc0000000000000"
                                             "5580000000000fffffffaffffffff0200000002fb000000260064006f0063006b005700690064006700650074005f0066006100760"
                                             "06f00720069007400650000000000ffffffff000000aa00fffffffb0000001e0064006f0063006b005700690064006700650074005"
                                             "f00660069006e006400000002490000006d0000006d00ffffff0000044c0000027600000004000000040000000800000008fc000000"
                                             "01000000020000000300000016006d00610069006e0054006f006f006c0042006100720100000000ffffffff00000000000000000000"
                                             "00220074006f006f006c004200610072005f006e006100760065006700610074006f00720100000203ffffffff000000000000000000"
                                             "00001a0074006f006f006c0042006100720072006500630065006e007401000002a9ffffffff0000000000000000)");
    QSettings settings(m_pathUser+"/data/setting.ini",
                       QSettings::IniFormat);
    //****************************
    // QSettings settings("Kirtasse", "setting");
    settings.beginGroup("MainWindow");
    m_MystyleName=settings.value("style","").toString();
   // m_WebFont=settings.value("font","Traditional Arabic,20,-1,5,50,0,0,0,0,0").toString();
    m_WebFont=settings.value("font","KacstBook,20,-1,5,50,0,0,0,0,0").toString();
    //m_WebFontTitle=settings.value("fontTitle","Andalus").toString();
     m_WebFontTitle=settings.value("fontTitle","KacstTitle").toString();
    m_WebColorBack=settings.value("bcolor","#ffffac").toString();
    m_WebFontColor=  settings.value("WebFontColor","#000000").toString();
    m_WebFontFindColor=settings.value("WebFontFindColor","#aa5500").toString();
    m_WebFontPrefertColor=settings.value("WebFontPrefertColor","#264c00").toString();
    m_WebFontTitleColor=settings.value("WebFontTitleColor","#ff0000").toString();
    m_recentNbr=settings.value("recentNbr",7).toInt();
    m_pathCostm=settings.value("pathCostm",m_pathUser+"/books").toString();
    Messages->m_pathCostum=settings.value("pathCostm",m_pathUser+"/books").toString();

    ui->actionTreeD->setChecked(settings.value("isThreeD",false).toBool())   ;
    m_WebCadre=settings.value("WebCadre",false).toBool();
#if QT_VERSION >= 0x040600
    view->threeD=settings.value("isThreeD",false).toBool();
#endif
    this->restoreGeometry(settings.value("geo_data").toByteArray());
    this->restoreState( settings.value("layout_data",layo_data).toByteArray());
    settings.endGroup();
    QFont font;
    font.fromString(m_WebFont);
    m_txtBrowser->setFont(font);
    settings.beginGroup("MainWindow");
    QApplication::setStyle(QStyleFactory::create( m_MystyleName));
}

void MainWindow::on_action_font_triggered()//تغيير الخط
{
    bool ok = false;
    QFont police =QFontDialog::getFont(&ok,  m_txtBrowser->font(), this,trUtf8(("اختيار خط الصفحة")));

    if (ok){
        m_txtBrowser->setFont(police);
        m_WebFont=police.toString();
    }
}

void MainWindow::on_action_close_triggered()
{
   // qApp->quit();
    if(this->close()==true)
        qApp->quit();
}

void MainWindow::on_action_about_triggered()//حول البرنامج
{
    About *dlg=new About(this);

    if ( dlg->exec() == QDialog::Accepted|| QDialog::Rejected){
    }
}

void MainWindow::on_actionOption_triggered()
{
    Dialogoption *dlgop=new Dialogoption(this);
    dlgop->colorBack=m_WebColorBack;
    dlgop->colorFont=m_WebFontColor;
    dlgop->colorFind=m_WebFontFindColor;
    dlgop->colorPrefer=m_WebFontPrefertColor;
    dlgop->colorTitle=m_WebFontTitleColor;
    dlgop->recentNbr=m_recentNbr;
    dlgop->pathCostm=m_pathCostm;
    dlgop->webCadre=m_WebCadre;
    QFont font;
    font.fromString(m_WebFont);
    dlgop->fontName=font;
    dlgop->fontTitleName=m_WebFontTitle;
    dlgop->themesStyle=m_MystyleName;
    dlgop->recharge();
    if ( dlgop->exec() == QDialog::Accepted ){
        m_WebColorBack=   dlgop->colorBack;
        m_WebFontColor=  dlgop->colorFont;
        m_WebFontFindColor=dlgop->colorFind;
        m_WebFontPrefertColor= dlgop->colorPrefer;
        m_WebFontTitleColor = dlgop->colorTitle;
        m_txtBrowser->setFont(dlgop->fontName);
        m_WebFont= dlgop->fontName.toString();
        m_WebCadre=dlgop->webCadre;
        m_MystyleName=  dlgop->themesStyle;
        m_recentNbr= dlgop->recentNbr;
        m_pathCostm=dlgop->pathCostm;
        m_WebFontTitle=dlgop->fontTitleName;
        QApplication::setStyle(QStyleFactory::create( m_MystyleName));
        if (m_currentBookIndex>0){
            convert_text(DataBook->bookNass[m_currentBookIndex]);
        }
    }
}

void MainWindow::on_actionRemoveTechkil_triggered()
{
    if(ui->actionRemoveTechkil->isChecked()){
        DataBook->removeTechkile=true;
    }else{
         DataBook->removeTechkile=false;
    }
    bookValueChanged(DataBook->currentPosition[m_currentBookIndex]);
}
//fahrrase ***  تحرير الفهرسةوالكتاب**********************************
void MainWindow::add_intree(bool child)//اظافة عنصر الى الفهرسة
{
    QString text=m_txtBrowser->textCursor().selectedText();
    if (text.isEmpty()){ return;}
    QTreeWidgetItem *curentitem;//العنصر المحدد
    QTreeWidgetItem *item;//العنصر الذي سنظيفه
    curentitem= m_treeFahras[m_currentBookIndex]->currentItem();
    if (child==false){ //اظافة عنصر جديد بعد المحدد
        if (!curentitem){                   //اذا لم يكن هناك تحديد سيظاف الى الجذر
            item= new QTreeWidgetItem(m_treeFahras[m_currentBookIndex]);
        }else{        // اما ان كان هناك عنصر محدد سيظاف بعده
            item= new QTreeWidgetItem(curentitem->parent(),curentitem);
            if (!curentitem->parent()){    //اذا لم يكن له اب سيضاف الى الجذر بعد المحدد
                item= new QTreeWidgetItem(m_treeFahras[m_currentBookIndex],curentitem);
            }
        }
    }
    if (child==true){             //اظافة ابن الى المحدد
        if (!curentitem){ return;}                   //اذا لم يكن هناك تحديد سيخرج
        item= new QTreeWidgetItem(curentitem);
        if ( item->parent()){
            item->parent()->setExpanded(true);
        }
    }
    item->setText(0,text );

    item->setData(1,1,DataBook->currentPosition[m_currentBookIndex]+1);
    item->setSelected(true);
    m_treeFahras[m_currentBookIndex]->setCurrentItem(item);//تفعيل العنصر المظاف
    m_treeFahrass_modified[m_currentBookIndex]=true;
}

void MainWindow::itemFahrasAdd()
{
     add_intree(false);
}

void MainWindow::itemFahrasAddChild()
{
     add_intree(true);
}

void MainWindow::on_action_edit_triggered()  //تحرير الفهرسة
{
  if (!m_BookName[m_currentBookIndex].isEmpty()){
        m_txtBrowser->setReadOnly(false);
      m_txtBrowser->setUndoRedoEnabled(true);
       ui->tabWidget->setTabText(ui->tabWidget->currentIndex(),trUtf8("تحرير : ")+m_BookTitle[m_currentBookIndex]);
               ui->frameEdit->setVisible(true);//اظهار ادوات التحرير
        m_treeFahras[m_currentBookIndex]->setDragDropMode(QAbstractItemView::InternalMove);//تفعيل عملية النقل بالفأرة
        m_treeFahras[m_currentBookIndex]->setSelectionMode(QAbstractItemView::ExtendedSelection);
        m_toolEditFahrass[m_currentBookIndex]=true;
    }
}

void MainWindow::itemFahrasRemove()//حذف عنصر من الفهرسة
{
    if (Messages->treeviewItemRemove(m_treeFahras[m_currentBookIndex])==true){
        m_treeFahrass_modified[m_currentBookIndex]=true;}
}

void MainWindow::itemFahrasMoveDown()//نقل عنصر للاسفل في الفهرسة
{
    if (Messages->treeviewItemDown(m_treeFahras[m_currentBookIndex])==true){
        m_treeFahrass_modified[m_currentBookIndex]=true;}
}

void MainWindow::itemFahrasMoveUp()//نقل عنصر للاعلى في الفهرسة
{
    if (Messages->treeviewItemUp(m_treeFahras[m_currentBookIndex])==true){
        m_treeFahrass_modified[m_currentBookIndex]=true;}
}

void MainWindow::menuSaveFahrass()//قائمة حفظ الفهرسة المحررة
{
     QString booktitle=m_BookTitle[m_currentBookIndex];

    saveFahrass(m_currentBookIndex);
}

void MainWindow::saveBookEndFahras()//زر حفظ الفهرسة المحررة
{
      if (m_treeFahrass_modified[m_currentBookIndex]==true){
        saveFahrass(m_currentBookIndex);
    }
     if (m_book_modified[m_currentBookIndex]==true){
         saveCurrentBook(m_currentBookIndex);
     }
}

void MainWindow::itemFahrasRename()
{
    QTreeWidgetItem *item=m_treeFahras[m_currentBookIndex]->currentItem();
    if(!item){ return;}
    QInputDialog *dff=new QInputDialog(this);
    dff->setOkButtonText(trUtf8("موافق"));
    dff->setLayoutDirection(Qt::RightToLeft);
    dff->setCancelButtonText(trUtf8("الغاء"));
    dff->setLabelText(trUtf8("ادخل اسما جديدا"));
    dff->setWindowTitle(trUtf8("اعادة تسمية العنصر"));
    dff->setTextValue(item->text(0));
    if (dff->exec()==QInputDialog::Accepted ){
        QString  newtext = dff->textValue();
        if (newtext.isEmpty()){ return;}
        item->setText(0,newtext);
        m_treeFahrass_modified[m_currentBookIndex]=true;
    }
}

void  MainWindow::saveFahrass(int index)
{
    Messages->m_pathCostum=m_pathCostm;
    if ( Messages->fahrasSave(m_treeFahras[index],m_BookName[index])==true){
        QMessageBox::information(this,trUtf8("معلومات"), trUtf8("تمت عملية حفظ الفهرسة بنجاح"));

    }else{
        QMessageBox::information(this,trUtf8("خطأ"), trUtf8("خطأ في كتابة الملف"));
    }
    m_treeFahrass_modified[index]=false;
}

void MainWindow::on_pushButtonEditClose_clicked()
{
    m_txtBrowser->setReadOnly(true);
    m_txtBrowser->setUndoRedoEnabled(false);
    ui->tabWidget->setTabText(ui->tabWidget->currentIndex(),m_BookTitle[m_currentBookIndex]);    
    ui->frameEdit->setVisible(false);
    m_treeFahras[m_currentBookIndex]->setDragDropMode(QAbstractItemView::NoDragDrop);
    m_treeFahras[m_currentBookIndex]->setSelectionMode(QAbstractItemView::SingleSelection);

}
//text browser***عمليات على النص**********************************
void MainWindow::anchorClicked(QUrl txtUrl)
{
  QString textCode=txtUrl.toString();
   if (textCode.isEmpty()) {return;}
   if (textCode.contains("www.intro.com")){
#if QT_VERSION >= 0x040600
      ui->textBrowser_0->setVisible(false);
      ui->frame_anim->setVisible(true);

      view->chargeLevelOne();
       view->setFocus();
#endif
       return;
   }
   if (textCode.contains("http://")){
        m_txtBrowser->setOpenExternalLinks(true);
    }else{
        m_txtBrowser->setOpenExternalLinks(false);

        QString nameTexte=textCode.section('/', 0,0);
        QString bookTexte=textCode.section('/', 1,1);
        QString authorTexte=textCode.section('/', 2,2);
        QString idBookTexte=textCode.section('/', 3,3);
        QString pageTexte=textCode.section('/', -1);

       QVariant pos=pageTexte;
        if (m_BookName[m_currentBookIndex]==idBookTexte){
            bookValueChanged(pos.toInt());
        }else{
            open_dataBase(idBookTexte,bookTexte,authorTexte,0);
             bookValueChanged(pos.toInt());
        }
    }
}

void MainWindow::highlighted(QUrl txtUrl)
{
    QString textCode=txtUrl.toString();
    if (textCode.isEmpty()|| textCode.contains("www.intro")) {
        ui->statusBar->showMessage("");
        return;
    }  
    if (textCode.contains("http://")){     
        ui->statusBar->showMessage(txtUrl.toString());
    }else{
        QString nameTexte=textCode.section('/', 0,0);
        QString bookTexte=textCode.section('/', 1,1);
        QString authorTexte=textCode.section('/', 2,2);
        ui->statusBar->showMessage(nameTexte +trUtf8(" كتاب :")+bookTexte+trUtf8(" المؤلف :")+authorTexte);
    }
}

void MainWindow::on_actionHiperlink_triggered()
{
    if (m_txtBrowser->textCursor().selectedText().isEmpty()){ return;}
    QString oldtxt=m_txtBrowser->textCursor().selectedText();

    Wizard=new ClassWizard(this);
    Wizard->setWizardStyle(QWizard::ModernStyle);
    if (Wizard->exec()==QDialog::Accepted) {
       // QMessageBox::information(this,"", Wizard->urlTexte);
        QString urltext="<a href='" +Wizard->urlTexte+"'>"+oldtxt+"</a>";
        m_txtBrowser->textCursor().insertHtml(urltext);
        DataBook->updatPage(oldtxt,urltext,false);
       m_book_modified[m_currentBookIndex]=true;
        m_txtBrowser->document()->setModified(false);
    }
}

void MainWindow::convert_text(QString txt)//تحويل بيانات النص
{
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    txt.replace(QByteArray("\n"), QByteArray("<br>"));
    txt.replace(QByteArray("\r"), QByteArray("<br>"));
    //*******************************************
    if (txt.contains("$")){
        txt.replace("$", "");
    }

    int id=DataBook->currentPosition[m_currentBookIndex]+1;
    QVariant dd=id;
    QTreeWidgetItem *item=new QTreeWidgetItem;
    QList<QTreeWidgetItem *> found =
            m_treeFahras[m_currentBookIndex]->findItems(
                    dd.toString(),Qt::MatchExactly | Qt::MatchRecursive,1);//تنشاء قائمة بكل العناصر

    foreach (item, found){
        m_treeFahras[m_currentBookIndex]->setCurrentItem(item);
        //    QMessageBox::information(this,trUtf8("llop"),item->text(0));
        txt.replace( item->text(0)+"<br>","< font face='"+m_WebFontTitle+"' color='"+m_WebFontTitleColor+"'> "+item->text(0)+"</font><br>");
        txt.replace("  "+ item->text(0),"< font face='"+m_WebFontTitle+"' color='"+m_WebFontTitleColor+"'><br> "+item->text(0)+"</font><br>");
        txt.replace("<br>"+ item->text(0),"< font face='"+m_WebFontTitle+"' color='"+m_WebFontTitleColor+"'><br> "+item->text(0)+"</font><br>");
        txt.replace( item->text(0)+"<br>","< font face='"+m_WebFontTitle+"' color='"+m_WebFontTitleColor+"'> "+item->text(0)+"</font><br>");
        txt.replace( item->text(0)+" <br>","< font face='"+m_WebFontTitle+"' color='"+m_WebFontTitleColor+"'> "+item->text(0)+"</font><br>");
        txt.replace( item->text(0)+" :","< font face='"+m_WebFontTitle+"' color='"+m_WebFontTitleColor+"'> "+item->text(0)+" :</font><br>");
        txt.replace( item->text(0)+":","< font face='"+m_WebFontTitle+"' color='"+m_WebFontTitleColor+"'> "+item->text(0)+" :</font>");
        txt.replace( item->text(0)+".","< font face='"+m_WebFontTitle+"' color='"+m_WebFontTitleColor+"'> "+item->text(0)+". </font><br>");

        if(txt.trimmed()== item->text(0).trimmed()){
            txt="< font face='"+m_WebFontTitle+"' color='"+m_WebFontTitleColor+"' > "+item->text(0)+" </font>";
        }
    }

    //********************************************
    QRegExp rxi("_____+");
    QRegExp rxd("ـــــ+");
    txt.replace(rxi," < font size='1'><br>__________");
    txt.replace(rxd," < font size='1'><br>__________");
    txt.replace("صلى الله عليه وسلم","< font color='"+m_WebFontPrefertColor+"' >صلى الله عليه وسلم</font> ");
    txt.replace("C تعالى","< font color='"+m_WebFontPrefertColor+"' >رحمه الله تعالى</font> ");
    txt.replace("{","< font color='"+m_WebFontPrefertColor+"' >﴿</font> ");
    txt.replace("}","< font color='"+m_WebFontPrefertColor+"' >﴾</font> ");
    txt.replace("رضي الله عنهم ",trUtf8("< font color='")+m_WebFontPrefertColor+trUtf8("'>رضي الله عنهم </font> "));
    txt.replace("رضي الله عنه ",trUtf8("< font color='")+m_WebFontPrefertColor+trUtf8("'>رضي الله عنه </font> "));
    txt.replace("رضي الله عنهما ",trUtf8("< font color='")+m_WebFontPrefertColor+trUtf8("' >رضي الله عنهما </font> "));
    txt.replace(" A ",trUtf8("< font color='")+m_WebFontPrefertColor+trUtf8("'> صلى الله عليه سلم </font> "));
    txt.replace("Bه",trUtf8("< font color='")+m_WebFontPrefertColor+trUtf8("'>رضي الله عنه </font> "));
    txt.replace(" D ",trUtf8("< font color='")+m_WebFontPrefertColor+trUtf8("'>  تعالى </font> "));
    txt.replace(" E ",trUtf8("< font color='")+m_WebFontPrefertColor+trUtf8("'> عليه السلام </font> "));

    if (txt.contains("**")){
        QRegExp rx("(\\d\\d? )[(]");
        txt.replace(rx,"<br>(");
        QRegExp rx1("(\\d\\d?)[(]");
        txt.replace(rx1,"<br>(");
        txt.replace(") (",")<br>(");
        txt.replace(")(",")<br>(");
    }
    txt.replace("<br><br>","<br>");
    txt.replace("<br> <br>","<br>");
    txt.replace("<br>  <br>","<br>");
    QString bgrcolor = "<body bgcolor='"+m_WebColorBack+"'>< font color='"+m_WebFontColor+"' >";
    //  m_txtBrowser->setPlainText(bgrcolor+ txt +  "</font></body>");
    //m_txtBrowser->setHtml(bgrcolor+ txt +  "</font></body>");
    if(m_WebCadre==true){
        QString table1= "<table width='100%'  height='100%' border='0' cellspacing='0'style='margin-left: -4px; margin-right: -28px; margin-top: -4px;margin-bottom: -4px'>"
                        "<tr style='font-size:8px';height='24';>"
                        "<th width='24' height='24' scope='col'><img src='file:///"+m_pathApp+"/data/images/top_left.png' width='24' height='24' /></th>"
                        "<td   width='100%' scope='col' background='file:///"+m_pathApp+"/data/images/top.png'  /td>"
                        "<th width='24' scope='col'><img src='file:///"+m_pathApp+"/data/images/top_right.png' width='24' height='24' /></th>"
                        "</tr>"
                        "<tr>"
                        "<td height='100%' background='file:///"+m_pathApp+"/data/images/left.png'/td>"
                        "<td><p style='margin-left: 5px; margin-right: 5px; margin-top: 5px;margin-bottom: 5px'>";
        QString table2="</p></td>"
                       " <td background='file:///"+m_pathApp+"/data/images/right.png'/td>"
                       "</tr>"
                       "<tr style='font-size:8px'; height='24';>"
                       "<td ><img src='file:///"+m_pathApp+"/data/images/bot_left.png' width='24' height='24' /></td>"
                       "<td background='file:///"+m_pathApp+"/data/images/bot.png' /td>"
                       "<td><img src='file:///"+m_pathApp+"/data/images/bot_right.png' width='24' height='24' /></td>"
                       "</tr>"
                       "</table>";

        m_txtBrowser->setHtml(bgrcolor+table1+ txt.trimmed() +table2+"</font></body>");
    }else{
        m_txtBrowser->setHtml(bgrcolor+ txt.trimmed() +"</font></body>");
    }
}
//add end update books***اضافة الكتب وتحريرها*********************
void MainWindow::on_action_import_triggered()//استراد ملفات نصية
{
      dialogconvert *dlgc=new dialogconvert(this);
     dlgc->m_pathCostum=m_pathCostm;
  if ( dlgc->exec() == QDialog::Accepted ){
       charge_groupe();
  }
}
void MainWindow::menu_BookRemove()//حذف الكتاب
{
    QTreeWidgetItem *item=ui->treeWidget_books->currentItem();
    if (!item->data(1,1).isNull()){
        QString myiddata=item->data(1,1).toString();
        QMessageBox msgBox;
        msgBox.setText(trUtf8("هل تريد حذف : ") + item->text(0)+trUtf8(" ؟"));
        msgBox.setInformativeText(trUtf8("انقر على نعم لحذفه من المكتبة فقط \n")+trUtf8("او نعم للكل لحذفه من المكتبة ومن جهازك"));
        msgBox.setDetailedText(trUtf8("اذا نقرت على نعم للكل سيتم حذف الكتاب من الدليل التالي ومن المكتبة\n")+m_pathCostm+myiddata);
        msgBox.setIcon(QMessageBox::Question);
        msgBox.setLayoutDirection(Qt::RightToLeft);
        msgBox.setWindowTitle(trUtf8("تأكيد الحذف"));
        msgBox.setStandardButtons(QMessageBox::YesAll | QMessageBox::Yes | QMessageBox::Cancel);
        msgBox.setDefaultButton(QMessageBox::YesAll);
        int ret = msgBox.exec();
        switch (ret) {
                case QMessageBox::YesAll:
                    Messages->treeMenuRemoveBook(myiddata,true);
                    charge_groupe();
                    break;
                case QMessageBox::Yes:
                    Messages->treeMenuRemoveBook(myiddata,false);
                    charge_groupe();
                    break;
                case QMessageBox::Cancel:
                    break;
                default:
                    break;
                }
    }
}
void MainWindow::menu_BookUpdat()  //تغيير بيانات الكتاب
{
    QTreeWidgetItem *item=ui->treeWidget_books->currentItem();
    dialogupdat *dlgc=new dialogupdat(this);
    dlgc->m_pathCostum=m_pathCostm;
    dlgc->BookName=item->data(1,1).toString();
    dlgc->addGroupId=item->parent()->data(2,1).toString();
    dlgc->bookTitle=item->text(0);
    dlgc->bookAutor=item->text(1);
    dlgc->bookBetaka=item->text(2);
    dlgc->recharge();
    if ( dlgc->exec() == QDialog::Accepted ){
      charge_groupe();
    }
}
void MainWindow::menu_BookPath()//معرفة مسار الكتاب
{
    QTreeWidgetItem *item=ui->treeWidget_books->currentItem();
    if (!item->data(1,1).isNull()){
        QString name=item->data(1,1).toString();
        QString path;
        QFile file;
        if(file.exists(m_pathCostm + "/" + name)){
            path=m_pathCostm + "/" + name;
        }else if(file.exists(m_pathApp + "/books/" + name)){
            path=m_pathApp + "/books/" + name;
        }else{
            path=name + trUtf8(" : غير موجود في الجهاز");
        }
        QMessageBox::information(this,trUtf8("مسار الكتاب"),path);
    }
}
void MainWindow:: menu_Add(bool categorie)
{
    QInputDialog *dff=new QInputDialog(this);
       dff->setOkButtonText(trUtf8("موافق"));
       dff->setLayoutDirection(Qt::RightToLeft);
       dff->setCancelButtonText(trUtf8("الغاء"));
      if (categorie==true){
          dff->setLabelText(trUtf8("ادخل اسما للقسم الجديد"));
          dff->setWindowTitle(trUtf8("قسم جديد"));
      }else{
          dff->setLabelText(trUtf8("ادخل اسما للمجموعة الجديدة"));
          dff->setWindowTitle(trUtf8("مجموعة جديدة"));
      }

       QString text;
       if (dff->exec()==QInputDialog::Accepted )
       {
           text=dff->textValue();
           //***********
           QVariant newId;
           newId=Messages->genirateId(ui->treeWidget_books);
           //*************
           QTreeWidgetItem *curentitem;//العنصر المحدد
           QTreeWidgetItem *item;//العنصر الذي سنظيفه
           curentitem= ui->treeWidget_books->currentItem();
           if (categorie==true){                   //اذا لم يكن هناك تحديد سيظاف الى الجذر
               item= new QTreeWidgetItem(ui->treeWidget_books);

           }else{
               if (!curentitem->parent()){                   //اذا لم يكن هناك تحديد سيظاف الى الجذر
                   item= new QTreeWidgetItem(curentitem);
               }else{        // اما ان كان هناك عنصر محدد سيظاف بعده
                   item= new QTreeWidgetItem(curentitem->parent());
               }
           }
           item->setText(0,text );
           item->setData(2,1,newId.toString());
           item->setIcon(0,m_iconGroup);
           item->setSelected(true);
           //  curentitem->setSelected(false);
           ui->treeWidget_books->setCurrentItem(item);//تفعيل العنصر المظاف
           m_treeGroup_modified=true;
           if (m_treeGroup_modified==true){
               int reponse = QMessageBox::warning(this, trUtf8("تنبيه"), trUtf8("هل تريد حفظ التغييرات المدخلة على مجموعة الكتب ") , QMessageBox::Yes | QMessageBox::No);
               if (reponse == QMessageBox::Yes){
                   if ( Messages->treeSaveGroupe(ui->treeWidget_books)){
                       QMessageBox::information(this,trUtf8("معلومات"), trUtf8("تمت عملية حفظ مجموعة الكتب بنجاح"));
                       m_treeGroup_modified=false;
                   }
               }
           }
       }
}

void MainWindow::menu_CategorieAdd()
{
    menu_Add(true);
}

void MainWindow::menu_GroupeAdd() //اضافة مجمعة جديدة الى الشجرة
{
   menu_Add(false);
}
void MainWindow::menu_GroupeRemove()//حذف المجموعة
{
    QTreeWidgetItem *item=ui->treeWidget_books->currentItem();
    if (item->childCount()>0){
        QMessageBox::information(this,trUtf8("تنبيه"),trUtf8("المحموعة تحتوي على عناصر تحتهاقم بحذف هذه العناصر أولا"));
    }else{
        int reponse = QMessageBox::question(this, trUtf8("معلومات"), trUtf8("هل تريد حذف المجموعة المحددة؟ ") , QMessageBox::Yes | QMessageBox::No);
        if (reponse == QMessageBox::Yes){
            if (Messages->treeviewItemRemove(ui->treeWidget_books)==true){
                m_treeGroup_modified=true;}
        }
    }
}
void MainWindow::menu_GroupeRename()  //اعادة تسمية المجموعة
{
    QTreeWidgetItem *item=ui->treeWidget_books->currentItem();
    QInputDialog *dff=new QInputDialog(this);
    dff->setOkButtonText(trUtf8("موافق"));
    dff->setLayoutDirection(Qt::RightToLeft);
    dff->setCancelButtonText(trUtf8("الغاء"));
    dff->setLabelText(trUtf8("ادخل النص الجديد"));
    dff->setWindowTitle(trUtf8("اعادة تسمية المجموعة"));
    dff->setTextValue(item->text(0));
    if (dff->exec()==QInputDialog::Accepted ){
        if (dff->textValue().isEmpty()){return;}
        item->setText(0,dff->textValue());
        m_treeGroup_modified=true;
    }
}
void MainWindow::on_action_addBoook_triggered()//اظافة كتاب
{
    Dialog* dlg=new Dialog(this);
    dlg->m_path=m_pathCostm;
    if ( dlg->exec() == QDialog::Accepted ){
        charge_groupe();
    }
}
void MainWindow::on_actionMdb_triggered()
{   
#ifdef Q_WS_X11
    mdbexport *dlg=new mdbexport(this);
    dlg->m_path=m_pathCostm;
    if ( dlg->exec() == QDialog::Accepted ){
        charge_groupe();
    }
#endif
#ifdef   Q_WS_WIN
    Dialogmdb *dlg=new Dialogmdb(this);
    dlg->m_path=m_pathCostm;
    if ( dlg->exec() == QDialog::Accepted ){
        charge_groupe();
    }
#endif
}
void MainWindow::saveCurrentBook(int index)
{
      DataBook->boocNumIndex=index;
    if (DataBook->saveBook()==true){
        QMessageBox::information(this,trUtf8("معلومات"), trUtf8("تمت عملية حفظ الكتاب بنجاح"));     
    }
      m_book_modified[index]=false;
}
void MainWindow::on_actionExport_triggered()//تصدير الكتاب
{
    if (m_BookName[m_currentBookIndex].isEmpty()){
        return;
    }
    Print* dlg=new Print(this);
    dlg->treeviw=m_treeFahras[m_currentBookIndex];
    dlg->curentPath=m_currentBookPath[m_currentBookIndex];
    dlg->m_WebColorBack=m_WebColorBack;                           //لون خلفية النص
    dlg->m_WebFontTitle=m_WebFontTitle;
    dlg-> m_WebFont=m_WebFont;                            //نوع النص
    dlg-> m_WebFontColor=m_WebFontColor;
    dlg-> m_WebFontTitleColor=m_WebFontTitleColor;
    dlg-> m_WebFontPrefertColor=m_WebFontPrefertColor;
    dlg-> m_bookTitle=m_BookTitle[m_currentBookIndex];
    dlg-> m_bookAuthor=m_BookAuthor[m_currentBookIndex];
    dlg->exec();
}
//navigation***التقل بين السجلات*******************************
void MainWindow::bookValueChanged(int pos)//التنقل بين السجلات حسب قيمة
{
    if (m_BookName[m_currentBookIndex].isEmpty()){
        AC_prevHistorie->setEnabled(false);
        AC_nextHistorie->setEnabled(false);
        return; }
    if(m_txtBrowser->document()->isModified()){
        DataBook->updatPage("",m_txtBrowser->document()->toPlainText().trimmed(),true);
        m_book_modified[m_currentBookIndex]=true;
    }
    DataBook->moveToPosition(pos);
    if (m_listHistoriePrev[m_currentBookIndex].isEmpty()){
        m_listHistoriePrev[m_currentBookIndex].append(DataBook->currentPosition[m_currentBookIndex]);
    }else if( m_listHistoriePrev[m_currentBookIndex].last()!=DataBook->currentPosition[m_currentBookIndex]){

        m_listHistoriePrev[m_currentBookIndex].append(DataBook->currentPosition[m_currentBookIndex]);
    }
    if ( m_listHistoriePrev[m_currentBookIndex].count()>1){
        AC_prevHistorie->setEnabled(true);
    }else{
        AC_prevHistorie->setEnabled(false);
    }
    if ( m_listHistorieNext[m_currentBookIndex].count()>1){
        AC_nextHistorie->setEnabled(true);
    }else{
        AC_nextHistorie->setEnabled(false);
    }
    convert_text(DataBook->bookNass[m_currentBookIndex]);
    QString page=DataBook->bookPage[m_currentBookIndex];
    QString part=DataBook->bookPart[m_currentBookIndex];

    m_label_page->setText(trUtf8("الصفحة :")+page +"  "+trUtf8("الجزء :")+part);
    m_label_progress_info->setText(trUtf8(" كتاب : ")+ui->tabWidget->tabText(ui->tabWidget->currentIndex()) +trUtf8(".  المؤلف : ")+m_BookAuthor[m_currentBookIndex]+". " +m_label_page->text());
}
void MainWindow::on_action_first_triggered()//السجل الاول
{
     bookValueChanged(0);
}
void MainWindow::on_action_next_triggered()//السجل التالي
{
    if (DataBook->currentPosition[m_currentBookIndex]==DataBook->rowsCount[m_currentBookIndex]){return;}
    bookValueChanged(DataBook->currentPosition[m_currentBookIndex]+1);
}
void MainWindow::on_action_prev_triggered()//السجل السابق
{
    if (DataBook->currentPosition[m_currentBookIndex]==0){return;}
    bookValueChanged(DataBook->currentPosition[m_currentBookIndex]-1);
}
void MainWindow::on_action_last_triggered()//السجل الاخير
{
    bookValueChanged(DataBook->rowsCount[m_currentBookIndex]);
}
void MainWindow::on_actionGotoPage_triggered()
{
    if (m_BookName[m_currentBookIndex].isEmpty()){  return; }
    dialoggoto *dlggo=new dialoggoto(this);
    dlggo->pathBook= m_currentBookPath[m_currentBookIndex]+"/book.xml";
    dlggo->rowCount=DataBook->rowsCount[m_currentBookIndex];
    dlggo->counter=DataBook->currentPosition[m_currentBookIndex];
    dlggo->updateValue();
    if (dlggo->exec() == QDialog::Accepted) {
        int id=dlggo->counter-1;
        bookValueChanged(id);
    }
}

void MainWindow::historieNext()
{
    if (m_BookName[m_currentBookIndex].isEmpty()){  return; }
    if ( m_listHistorieNext[m_currentBookIndex].isEmpty() ||  m_listHistorieNext[m_currentBookIndex].count()<1){
        AC_nextHistorie->setEnabled(false);
        return; }
    int p= m_listHistorieNext[m_currentBookIndex].last();
    m_listHistorieNext[m_currentBookIndex].removeLast();
    if ( m_listHistorieNext[m_currentBookIndex].count()<1 ){
        AC_nextHistorie->setEnabled(false);
    }
    m_listHistoriePrev[m_currentBookIndex].append(p);
    AC_prevHistorie->setEnabled(true);
    DataBook->moveToPosition(p);
    convert_text(DataBook->bookNass[m_currentBookIndex]);
    QString page=DataBook->bookPage[m_currentBookIndex];
    QString part=DataBook->bookPart[m_currentBookIndex];
    m_label_page->setText(trUtf8("الصفحة :")+page +"  "+trUtf8("الجزء :")+part);
    m_label_progress_info->setText(trUtf8(" كتاب : ")+ui->tabWidget->tabText(ui->tabWidget->currentIndex()) +trUtf8(".  المؤلف : ")+m_BookAuthor[m_currentBookIndex]+". " +m_label_page->text());

}

void MainWindow::historiePrev()
{
  if (m_BookName[m_currentBookIndex].isEmpty()){  return; }
  if ( m_listHistoriePrev[m_currentBookIndex].isEmpty() || m_listHistoriePrev[m_currentBookIndex].count()<2){
       AC_prevHistorie->setEnabled(false);
      return; }

     int p=  m_listHistoriePrev[m_currentBookIndex].last();
     m_listHistoriePrev[m_currentBookIndex].removeLast();
     if ( m_listHistoriePrev[m_currentBookIndex].count()<2)
     {
         AC_prevHistorie->setEnabled(false);
     }
     m_listHistorieNext[m_currentBookIndex].append(p);
       AC_nextHistorie->setEnabled(true);

    int i=  m_listHistoriePrev[m_currentBookIndex].last();
     DataBook->moveToPosition(i);
      convert_text(DataBook->bookNass[m_currentBookIndex]);
     QString page=DataBook->bookPage[m_currentBookIndex];
     QString part=DataBook->bookPart[m_currentBookIndex];
     m_label_page->setText(trUtf8("الصفحة :")+page +"  "+trUtf8("الجزء :")+part);
     m_label_progress_info->setText(trUtf8(" كتاب : ")+ui->tabWidget->tabText(ui->tabWidget->currentIndex()) +trUtf8(".  المؤلف : ")+m_BookAuthor[m_currentBookIndex]+". " +m_label_page->text());
}
//find***عمليات البحث***********************************
void MainWindow::on_pushButton_gofind_clicked()
{
    ui->pushButton_gofind->setCursor(QCursor(Qt::WaitCursor));
    Findbook->searchInTreeview(ui->treeWidget_curaan,ui->lineEdit_find_cur->text(),0);
    ui->pushButton_gofind->setCursor(QCursor(Qt::ArrowCursor));
}
void MainWindow::on_lineEdit_find_cur_textChanged(QString searchString)
{
    if (searchString.isEmpty()){

        Findbook->searchInTreeview(ui->treeWidget_curaan,ui->lineEdit_find_cur->text(),0);
    }
}
void MainWindow::find_favo_textChanged(QString searchString)//البحث في شجرة المفضلة
{
    Findbook->searchInTreeview(ui->treeWidget_fav,searchString,0);
}
void MainWindow::searchInTreeFah(QString searchString)//البحث في شجرة الفهرسة
{
    Findbook->searchInTreeview(m_treeFahras[m_currentBookIndex],searchString,0);
}
void MainWindow::searchInTreebook(QString searchString)//البحث في شجرة الكتب
{
    int colum=0;
    if (m_find_tree_book==false){
        colum=1;
    }
    Findbook->searchInTreeview(ui->treeWidget_books,searchString,colum);
}
void MainWindow::showResultFind(QTreeWidgetItem* item)//تفعيل عناصر شجرة البحث
{
     QVariant bkpage=item->data(0,1);
    int  tabcount=ui->tabWidget->count();
    for(int r=0;r<tabcount;++r){
    QTextBrowser *txtBrowser = ui->tabWidget->widget(r)->findChild<QTextBrowser *>();
    QString txtname=txtBrowser->objectName();
    QString  str = txtname.section('_', -1);
    QVariant indx=str;
        if (m_BookName[indx.toInt()]==item->data(3,1).toString()){
            ui->tabWidget->setCurrentIndex(r);
            bookValueChanged(bkpage.toInt()-1);
            Findbook->searchInDoc( m_txtBrowser->document(),m_textfind,QColor(m_WebFontFindColor));
            return;
        }
    }
 QString x = item->data(3,1).toString();
    open_dataBase(x,item->text(3),item->text(4),bkpage.toInt()-1);
    m_isTefsir[m_currentBookIndex]=item->data(2,1).toBool();
    Findbook->searchInDoc( m_txtBrowser->document(),m_textfind,QColor(m_WebFontFindColor));
}
void MainWindow::find_in_curbook()//البحث في الكتاب الحالي
{
    Findbook->pathCostum= m_currentBookPath[m_currentBookIndex] ;
    if (Findbook->isFindRuned==true){ return;}
    if (m_BookName[m_currentBookIndex].isEmpty())  { return;}
    if (m_lineEditSearchInDoc->text().isEmpty()){ return;}
    m_textfind=m_lineEditSearchInDoc->text();
     ui->dockWidget_find->setShown(true);
    ui->treeWidgetFind->clear();
    ui->treeWidgetFind->setColumnWidth(0,500);
    ui->treeWidgetFind->setColumnWidth(1,30);
    ui->treeWidgetFind->setColumnWidth(2,50);
    ui->dockWidget_find->setShown(true);
   labelTextFind->setText(trUtf8("نص البحث  : ")+m_textfind);
    m_progressFind->setMaximum(DataBook->rowsCount[m_currentBookIndex]);
    m_progressFind->setVisible(true);
    BtnStopFind->setVisible(true);
    Findbook->findMultiFind=false;
    Findbook->findSawabik=true;
    Findbook->findToList=false;
    Findbook->resultCount=0;
    Findbook->isTefsir=m_isTefsir[m_currentBookIndex];
    Findbook-> findTitle=m_BookTitle[m_currentBookIndex];
    Findbook-> findAuthor=m_BookAuthor[m_currentBookIndex];
    Findbook-> findName=m_BookName[m_currentBookIndex];
    Findbook->findText=m_textfind;
    Findbook->progressBar1=m_progressFind;
    Findbook->label_progressImg=m_label_progressImg;
    Findbook->pushButtonStop=BtnStopFind;
    Findbook->treeView=ui->treeWidgetFind;
    Findbook->findOneBook(m_currentBookPath[m_currentBookIndex]);
}
void MainWindow::find_bookOrHautor()//البحث عن كتاب
{
    if (ui->actionFindBkOrHt->isChecked()){
        ui->actionFindBkOrHt->setToolTip(trUtf8("البحث عن مؤلف"));
        m_find_tree_book=false;
    }else{
         ui->actionFindBkOrHt->setToolTip(trUtf8("البحث عن كتاب"));
        m_find_tree_book=true;
    }


}

void MainWindow::on_actionFind_all_triggered()  // تنفيذ البحث في مجموعة الكتب
{
    if (Findbook->isFindRuned==true){ return;}
    Dialogfind* dlg=new Dialogfind(this);
    dlg->bookPath=m_pathCostm;
    if ( dlg->exec() == QDialog::Accepted ){
        m_textfind=dlg->findString;
        if ( m_textfind.length()<3){ return;}
        ui->treeWidgetFind->clear();
        ui->treeWidgetFind->setColumnWidth(0,500);
        ui->treeWidgetFind->setColumnWidth(1,30);
        ui->treeWidgetFind->setColumnWidth(2,50);
        ui->dockWidget_find->setShown(true);
        labelTextFind->setText(trUtf8("نص البحث  : ")+m_textfind);
        m_label_progress->setVisible(true);
        m_label_progressImg->setVisible(true);
        BtnStopFind->setVisible(true);
        Findbook->pathCostum=m_pathCostm;
        Findbook->findFirst=dlg->findFirst;
        Findbook->findToList=dlg->findList;
        Findbook->findMultiFind=dlg->MultiFind;
        Findbook->findAnd=dlg->findAnd;
        Findbook->findSawabik=dlg->findSawabik;
        Findbook->findText= m_textfind;
        Findbook->resultCount=0;
        Findbook->progressBar1=  m_progressFind;
        Findbook->pushButtonStop=BtnStopFind;
        Findbook->treeView=ui->treeWidgetFind;
        Findbook->labelProgress=m_label_progress;
        Findbook->label_progressImg=m_label_progressImg;
        Findbook->findAllBook();
    }
}

void MainWindow::search_stop()//توقيف عملية البحث
{
    Findbook ->stopFind=true;
}

void MainWindow::search_indoc()
{
   if (!m_lineEditSearchInDoc->text().isEmpty())
   {
        Findbook->findToList=false;
    if (Findbook->searchInDoc( m_txtBrowser->document(),m_lineEditSearchInDoc->text(),QColor(m_WebFontFindColor))==false)
    {
        QMessageBox::information(this,trUtf8("معلومات"), trUtf8("النص غير موجود في الصفحة"));
    }
}
}

void MainWindow::on_actionFindSave_triggered()
{
    if (ui->treeWidgetFind->topLevelItemCount()>0){
  Findbook->findText=m_textfind;
        if( Findbook->saveResultFind(ui->treeWidgetFind)==true){
            QMessageBox::information(this,trUtf8("معلومات"), trUtf8("تمت العملية الحفظ بنجاح"));
        }else{
            QMessageBox::information(this,trUtf8("خطأ"), trUtf8("لا يمكن كتابة الملف"));
        }
    }
}

void MainWindow::on_actionFindLoad_triggered()
{
      QFile file(QDir::homePath()+"/.kirtasse/data/ResultFind.xml");
      if (file.exists()){
          ui->treeWidgetFind->setColumnWidth(0,500);
          ui->treeWidgetFind->setColumnWidth(1,30);
          ui->treeWidgetFind->setColumnWidth(2,50);
          ui->treeWidgetFind->clear();
          Findbook->loadResultFind(ui->treeWidgetFind);
           m_textfind=  Findbook->findText;
          labelTextFind->setText(trUtf8("نص البحث  : ")+m_textfind);
      }else{
           QMessageBox::information(this,trUtf8("معلومات"), trUtf8("لا توجد نتائج سابقة"));
      }
}

//treeview***تفعيل الشجرات***********************************
void MainWindow::fahras_itemClicked(QTreeWidgetItem* item)//النقر على عنصر شجرة الفهرسة
{
    if ( m_toolEditFahrass[m_currentBookIndex]==false){
     bookValueChanged(item->data(1,1).toInt()-1);
    int index=m_txtBrowser->toPlainText().indexOf(item->text(0));
    if (index>0){
        QTextCursor cursor(m_txtBrowser->document());
        cursor.setPosition(index,QTextCursor::MoveAnchor);
        cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor);
        m_txtBrowser->setTextCursor(cursor);
    }
    m_treeFahras[m_currentBookIndex]->setCurrentItem(item);
}
}
void MainWindow::fahras_itemActivated(QTreeWidgetItem* item)
{
    DataBook->newPosition[m_currentBookIndex]=item->data(1,1).toInt()-1;
    bookValueChanged(item->data(1,1).toInt()-1);
    int index=m_txtBrowser->toPlainText().indexOf(item->text(0));
    if (index>0){
        QTextCursor cursor(m_txtBrowser->document());
        cursor.setPosition(index,QTextCursor::MoveAnchor);
        cursor.movePosition(QTextCursor::Down, QTextCursor::MoveAnchor);
        m_txtBrowser->setTextCursor(cursor);
    }
    m_treeFahras[m_currentBookIndex]->setCurrentItem(item);
}
void MainWindow::on_treeWidget_books_itemSelectionChanged()//تحديد عنصر الكتاب في الشجرة
{
    QTreeWidgetItem *item=ui->treeWidget_books->currentItem();
    if (!item->data(1,1).isNull()){
        QString   m_txtAnim=trUtf8("الكتاب :") +  item->text(0) +"\n"
                            + trUtf8("المؤلف :") +  item->text(1) +"\n"
                            +   item->text(2);
        m_txtBetaka->setText(m_txtAnim);
        startAnimation();
    }else{
        startAnimationBook();
    }
}

void MainWindow::on_treeWidget_curaan_itemActivated(QTreeWidgetItem* item)//تفعيل عنصر شجرة القرءان
{
        if (m_isTefsir[m_currentBookIndex]==true){
        ui->treeWidget_curaan->setCursor(QCursor(Qt::WaitCursor));
        QString mysora = item->data(1,1).toString().section('_', 0, 0);
        QString myaya = item->data(1,1).toString().section('_', -1);
        if (DataBook->findAya(mysora,myaya)==true)  {
            bookValueChanged(DataBook->currentPosition[m_currentBookIndex]);
            ui->treeWidget_curaan->setCursor(QCursor(Qt::ArrowCursor));
            return;
        }
    }
    ui->treeWidget_curaan->setCursor(QCursor(Qt::ArrowCursor));
}

void MainWindow::on_treeWidget_books_itemActivated(QTreeWidgetItem* item)//تفعيل عنصر شجرة الكتب
{
    QString x = item->data(1,1).toString();
    if (!x.isEmpty())
    {
          open_dataBase(x,item->text(0),item->text(1),0);
        QVariant tf = item->data(2,1).toString();
         m_isTefsir[m_currentBookIndex]=tf.toBool();
    }
}

void MainWindow::on_treeWidget_fav_itemActivated(QTreeWidgetItem* item)
{
    if (item->data(1,1).toString().isEmpty()){return;}
    QVariant bkpage=item->data(2,1);
    QVariant bknam=item->data(1,1);   
    if (bknam.toString()==m_BookName[m_currentBookIndex]){
        DataBook->newPosition[m_currentBookIndex]=bkpage.toInt();
        bookValueChanged(bkpage.toInt());
    }else{
        open_dataBase(item->data(1,1).toString(),item->text(1),item->text(2),bkpage.toInt());
    }
}

void MainWindow::on_treeWidget_books_customContextMenuRequested()//قائمة منسدلة فرعية لشجرة الكتب
{
    QTreeWidgetItem *item=ui->treeWidget_books->currentItem();
    if (!item->data(1,1).isNull()){
        QMenu menu(this);
        menu.setLayoutDirection(Qt::RightToLeft);
        menu.addAction(AC_open_book);
        menu.addAction(AC_openBookInNewTab);
        menu.addAction(AC_updat_book);
        menu.addSeparator();
        menu.addAction(AC_remove_book);
        menu.addSeparator();
        menu.addAction(AC_path_book);
        menu.exec(QCursor::pos());
    }else {
        QMenu menu(this);
        menu.setLayoutDirection(Qt::RightToLeft);
        menu.addAction(AC_add_categorie);
        menu.addAction(AC_add_groupe);
        menu.addAction(AC_rename_groupe);
        menu.addSeparator();
        menu.addAction(AC_remove_groupe);
        menu.exec(QCursor::pos());
    }
}

//favorite********************************************************
void MainWindow::on_actionFavSave_triggered()
{
    Messages->favorite_save(ui->treeWidget_fav);
}

void MainWindow::on_actionFavItemRen_triggered()
{
    QTreeWidgetItem *item=ui->treeWidget_fav->currentItem();
    if(!item){ return;}
    QInputDialog *dff=new QInputDialog(this);
    dff->setOkButtonText(trUtf8("موافق"));
    dff->setLayoutDirection(Qt::RightToLeft);
    dff->setCancelButtonText(trUtf8("الغاء"));
    dff->setLabelText(trUtf8("ادخل اسما جديدا"));
    dff->setWindowTitle(trUtf8("اعادة تسمية العنصر"));
    dff->setTextValue(item->text(0));
    if (dff->exec()==QInputDialog::Accepted ){
        QString  newtext = dff->textValue();
        if (newtext.isEmpty()){ return;}
        item->setText(0,newtext);
    }
}

void MainWindow::on_actionFavItemUp_triggered()
{
    QTreeWidgetItem *item=ui->treeWidget_fav->currentItem();
    if(!item){ return;}
    Messages->treeviewItemUp(ui->treeWidget_fav);
}

void MainWindow::on_actionFavItemDown_triggered()
{
    QTreeWidgetItem *item=ui->treeWidget_fav->currentItem();
    if(!item){ return;}
    Messages->treeviewItemDown(ui->treeWidget_fav);
}

void MainWindow::on_action_favorit_triggered()
{
    if (m_BookName[m_currentBookIndex].isEmpty()){ return;}
    dialogfavo *dlg=new dialogfavo(this);
    dlg->iconFolder=m_icondir;
    dlg->iconFile=m_icondfile;
    dlg->view=ui->treeWidget_fav;
    dlg->bookTitle=m_BookTitle[m_currentBookIndex];
    dlg->bookName=m_BookName[m_currentBookIndex];
    dlg->bookAut=m_BookAuthor[m_currentBookIndex];
    QVariant idbk=DataBook->currentPosition[DataBook->boocNumIndex];
    dlg->bookId=idbk.toString();
    dlg->charge_combo();
    dlg->exec() ;
}

void MainWindow::on_actionFavDelete_triggered()
{
    QTreeWidgetItem* item=ui->treeWidget_fav->currentItem();
    if(!item){ return;}
    QString text;
    if (item->childCount()>0){
        text= trUtf8("العنصر الذي تريد حذفه يحتوي على عناصر اخرى هل تريد حذفه رغم ذلك ؟");
    }else{
        text= trUtf8("هل تريد حذف العنصر المحدد");
    }
    int reponse = QMessageBox::warning(this, trUtf8("تنبيه"),text , QMessageBox::Yes | QMessageBox::No);
    if (reponse == QMessageBox::No){return;}
    Messages->treeviewItemRemove(ui->treeWidget_fav);
}
//tabs***الالسنة*************************************************
void MainWindow::on_actionNewTab_triggered()
{
    tabCreatTabNew();
}

void MainWindow::on_tabWidget_tabCloseRequested(int index)
{
    QTextBrowser *txtBrowser = ui->tabWidget->widget(index)->findChild<QTextBrowser *>();
    QString name=txtBrowser->objectName();
    QString  str = name.section('_', -1);
    if (!m_BookName[str.toInt()].isEmpty()){                              //حفظ قائمة الكتب السابقة

        if (txtBrowser->document()->isModified()){
            DataBook->updatPage("",txtBrowser->document()->toPlainText(),true);
            m_book_modified[str.toInt()]=true;
        }

        if (closeMessages(m_BookTitle[str.toInt()],str.toInt())==false){

            return;
        }

        QVariant idbk=DataBook->currentPosition[DataBook->boocNumIndex];
        Messages->recentChange(m_BookName[str.toInt()],m_BookTitle[str.toInt()],m_BookAuthor[str.toInt()],idbk.toString(),m_recentNbr,m_isTefsir[str.toInt()]);
        Messages->recentCharge();

    }
    m_BookName[str.toInt()]="";
    m_listTab.removeOne(str);
    ui->tabWidget->removeTab(index);
    ui->stackedWidget->removeWidget(ui->stackedWidget->widget(index));
    ui->stackedWidget->setCurrentIndex(ui->tabWidget->currentIndex());
    DataBook->claerBook(str.toInt());
    m_listHistoriePrev[str.toInt()].clear();
    m_listHistorieNext[str.toInt()].clear();
    if (ui->tabWidget->count()>1)
    {
        ui->tabWidget->setTabsClosable(true);
    }else{
        ui->tabWidget->setTabsClosable(false);
    }
}

void MainWindow::tabCreatFahrass()
{
    QGridLayout *gridLayout;
    gridLayout = new QGridLayout(ui->stackedWidget->currentWidget());
    gridLayout->setSpacing(3);
    gridLayout->setMargin(3);
    m_treeFahras[m_currentBookIndex] =new QTreeWidget(ui->stackedWidget->currentWidget());
    m_treeFahras[m_currentBookIndex]->headerItem()->setText(0,"");
    gridLayout->addWidget(m_treeFahras[m_currentBookIndex],0,0, 1, 1);
    m_treeFahras[m_currentBookIndex]->show();
    connect(m_treeFahras[m_currentBookIndex], SIGNAL(itemActivated(QTreeWidgetItem*,int)), this, SLOT(fahras_itemActivated(QTreeWidgetItem*)));
    connect(m_treeFahras[m_currentBookIndex], SIGNAL(itemClicked (QTreeWidgetItem* , int )), this, SLOT(fahras_itemClicked(QTreeWidgetItem*)));
    connect(lineEditFindFah, SIGNAL(textChanged(QString)), this, SLOT(searchInTreeFah(QString)));
    connect(expandTreeFah, SIGNAL(triggered()), m_treeFahras[m_currentBookIndex], SLOT(expandAll()));
    connect(colapsTreeFah, SIGNAL(triggered()),m_treeFahras[m_currentBookIndex], SLOT(collapseAll()));
}

void MainWindow::tabCreatTabNew()
{
    QIcon icon;
       icon.addPixmap(QPixmap(QString::fromUtf8(":/images/image/booki.png")), QIcon::Normal, QIcon::Off);
    if (ui->tabWidget->count()==10) {return;}
    QTabBar *m_tb;
    QTextBrowser *textBrowser;
        m_tb=new QTabBar(ui->tabWidget);//اظافة لسان
    ui->tabWidget->addTab(m_tb,icon,"");

            textBrowser=new QTextBrowser(m_tb);    //اظافة مربع نصالى للسان
    QGridLayout *mainLayout = new QGridLayout;
    mainLayout->setMargin(2);
    mainLayout->addWidget(textBrowser, 0, 0);
    m_tb->setLayout(mainLayout);
    QVariant d;
    for(int r=1;r<10;r++)    //تعريف وحيد للسان الجديد
    {
        d=r;
        if  ( m_listTab.lastIndexOf(d.toString())==-1)
        {
            m_listTab.append(d.toString());
            textBrowser->setObjectName("textBrowser_"+d.toString());
            m_currentBookIndex=d.toInt();
            break;
        }
    }
    QWidget *firstPageWidget = new QWidget;
    ui->stackedWidget->addWidget(firstPageWidget);
    ui->stackedWidget->setCurrentWidget(firstPageWidget);
    ui->tabWidget->setCurrentWidget(m_tb);
    ui->tabWidget->setTabText(ui->tabWidget->currentIndex(),trUtf8("مكتبة القرطاس"));
    //معرفة مربع النص في اللسان النشط
    m_txtBrowser = ui->tabWidget->currentWidget()->findChild<QTextBrowser *>();
    connect(textBrowser, SIGNAL(highlighted(const QUrl)), this, SLOT(highlighted(QUrl)));
    connect(textBrowser, SIGNAL(anchorClicked(const QUrl)), this, SLOT(anchorClicked(QUrl)));
    connect(textBrowser, SIGNAL(copyAvailable(bool)), ui->actionFahAddChild, SLOT(setEnabled(bool)));
    connect(textBrowser, SIGNAL(copyAvailable(bool)), ui->actionFahAddItem, SLOT(setEnabled(bool)));
    tabCreatFahrass();
}

void MainWindow::tabOpenInNewTab()
{
    tabCreatTabNew();
    menuOpenBook();
}

void MainWindow::on_tabWidget_currentChanged(int )
{
    m_txtBrowser = ui->tabWidget->currentWidget()->findChild<QTextBrowser *>();
    QString name=m_txtBrowser->objectName();
    QString  str = name.section('_', -1);
    m_currentBookIndex=str.toInt();;
    DataBook->boocNumIndex=str.toInt();

    if (ui->tabWidget->count()>1)
    {
        ui->tabWidget->setTabsClosable(true);
    }else{
        ui->tabWidget->setTabsClosable(false);
    }
    QFont font;
    font.fromString(m_WebFont);
    m_txtBrowser->setFont(font);
    bookValueChanged(DataBook->currentPosition[m_currentBookIndex]);

    if (m_toolEditFahrass[m_currentBookIndex]==true){
        ui->frameEdit->setVisible(true);//اظهار ادوات التحرير
    }else{
        ui->frameEdit->setVisible(false);
    }
         ui->stackedWidget->setCurrentIndex(ui->tabWidget->currentIndex());
}
//Animation************************************************
void MainWindow::startAnimation()
{
#if QT_VERSION >= 0x040600
    QPropertyAnimation *anim = new QPropertyAnimation(m_txtBetaka, "pos");
    anim->setEasingCurve(QEasingCurve::OutCirc);
    m_txtBetaka->setWordWrap(true);

   anim->setStartValue(QPointF(0, 0));
    anim->setEndValue(QPointF(300, 0));
   anim->setDuration(500);
    anim->setLoopCount(1); // forever
   anim->start();
#endif
}

void MainWindow::startAnimationBook()
{
#if QT_VERSION >= 0x040600
    QPropertyAnimation *anim = new QPropertyAnimation(m_txtBetaka, "pos");
    anim->setEasingCurve(QEasingCurve::OutBounce);
    m_txtBetaka->setPixmap(QPixmap(QString::fromUtf8(":/images/image/groupbook.png")));
    anim->setStartValue(QPointF(300,300));
    anim->setEndValue(QPointF(300,0));
    anim->setDuration(1000);
    anim->setLoopCount(1);
    anim->start();
#endif
}

void MainWindow::on_lineEdit_textChanged(QString )
{
    if (!ui->lineEdit->text().isNull()|!ui->lineEdit->text().isEmpty()){
        QString myid = ui->lineEdit->text().section('/', 0, 0);
        QString  myname=ui->lineEdit->text().section('/', 1, 1);
          QString myaut= ui->lineEdit->text().section('/',2,2);
 QString mypage= ui->lineEdit->text().section('/', -1);
         open_dataBase(myid, myname,myaut,mypage.toInt());
    }
}

//print***الطباعة************************************************
void MainWindow::on_actionPrint_triggered()
{
#ifndef QT_NO_PRINTER
    QPrinter printer(QPrinter::HighResolution);
    QPrintDialog *dlg = new QPrintDialog(&printer, this);
    if (m_txtBrowser->textCursor().hasSelection())
        dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection);
    dlg->setWindowTitle(tr("Print Document"));
    if (dlg->exec() == QDialog::Accepted) {
        m_txtBrowser->print(&printer);

    }
        delete dlg;
#endif
}

void MainWindow::on_actionPrintPreview_triggered()
{
#ifndef QT_NO_PRINTER
    QPrinter printer(QPrinter::HighResolution);
    QPrintPreviewDialog preview(&printer, this);
    connect(&preview, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreview(QPrinter*)));
    preview.exec();
#endif
}

void MainWindow::printPreview(QPrinter *printer)
{
#ifdef QT_NO_PRINTER
    Q_UNUSED(printer);
#else
    m_txtBrowser->print(printer);
#endif
}

void MainWindow::on_actionHelp_triggered()
{
    if( ui->tabIntro->isHidden())  {

        ui->tabWidget->insertTab(0,ui->tabIntro,trUtf8("مكتبة القرطاس"));
        ui->stackedWidget->insertWidget(0,ui->pageIntro);
    }
    ui->textBrowser_0->setVisible(true);
    ui->frame_anim->setVisible(false);
    ui->tabWidget->setCurrentWidget(ui->tabIntro);
    labelAnim->setText(trUtf8("التعليمات"));
    QFile file(m_pathApp+"/data/help.html");
    if (!file.exists()){
        ui->textBrowser_0->setText(trUtf8("ملف التعليمات  : ")+m_pathApp+"/data/help.html\n"+trUtf8("غير موجود"));
        return;
    }
    if (file.open(QIODevice::ReadOnly)){
        QByteArray data = file.readAll();
        QTextCodec *codec = Qt::codecForHtml(data);
        QString str = codec->toUnicode(data);
        str.replace("<img src=\"","<img src=\""+m_pathApp+"/data/");
        if (Qt::mightBeRichText(str)) {
            ui->textBrowser_0->setHtml(str);
 ui->textBrowser_0->setOpenLinks(true);
        }
        file.close();
    }
}
//***تعديل روابط الفهرسة************************************************
void MainWindow::on_actionOrganizeFahrasse_triggered()
{

DataBook->treeOrganizFahrass(m_treeFahras[m_currentBookIndex],m_currentBookPath[m_currentBookIndex]);

m_treeFahrass_modified[m_currentBookIndex]=true;
}


void MainWindow::on_actionPageIntro_triggered()
{
    if( ui->tabIntro->isHidden())  {

        ui->tabWidget->insertTab(0,ui->tabIntro,trUtf8("مكتبة القرطاس"));
        ui->stackedWidget->insertWidget(0,ui->pageIntro);
    }
    ui->textBrowser_0->setVisible(true);
       ui->frame_anim->setVisible(false);
    ui->tabWidget->setCurrentWidget(ui->tabIntro);
    labelAnim->setText(trUtf8(""));
 QFile file(":/images/image/intro.html");
 if (file.open(QIODevice::ReadOnly)){
     QByteArray data = file.readAll();
     QTextCodec *codec = Qt::codecForHtml(data);
     QString str = codec->toUnicode(data);
     if (Qt::mightBeRichText(str)) {

         ui->textBrowser_0->setHtml(str);
         ui->textBrowser_0->setOpenLinks(false);
     }
 }
  file.close();
}

void MainWindow::on_actionAnimGroup_triggered()
{
    ui->textBrowser_0->setVisible(false);
    ui->frame_anim->setVisible(true);
    view->chargeLevelOne();
    view->setFocus();
}

void MainWindow::on_actionAnimHistorie_triggered()
{
    ui->textBrowser_0->setVisible(false);
     ui->frame_anim->setVisible(true);


  int count=0;
  for (int i=0;i<15;i++){
      if (recentFileActs[i]->isVisible()){
          count++;
           view->recentFileActs[i]= recentFileActs[i];
      }

  }

  view->recentNbr=count+1;
     view->chargeRecent();
      view->setFocus();
}

void MainWindow::on_actionTreeD_toggled(bool checked)
{
    view->threeD=checked;
      view->setFocus();
}

void MainWindow::on_actionFindItemUp_triggered()
{
    QTreeWidgetItem *item=ui->treeWidgetFind->currentItem();
    if(!item){ return;}
    Messages->treeviewItemUp(ui->treeWidgetFind);
}

void MainWindow::on_actionFindItemDown_triggered()
{
    QTreeWidgetItem *item=ui->treeWidgetFind->currentItem();
    if(!item){ return;}
    Messages->treeviewItemDown(ui->treeWidgetFind);
}

void MainWindow::on_actionFindDelete_triggered()
{
    QTreeWidgetItem* item=ui->treeWidgetFind->currentItem();
    if(!item){ return;}
    QString text= trUtf8("هل تريد حذف العنصر المحدد");

    int reponse = QMessageBox::warning(this, trUtf8("تنبيه"),text , QMessageBox::Yes | QMessageBox::No);
    if (reponse == QMessageBox::No){return;}
    Messages->treeviewItemRemove(ui->treeWidgetFind);
}

void MainWindow::openRecentFile()
 {
     QAction *action = qobject_cast<QAction *>(sender());
     if (action){

         QVariant txtdata=action->data();
         QString myid = txtdata.toString().section('/', 0, 0);
         QString myaut= txtdata.toString().section('/', 2,2);
         QString  myname=txtdata.toString().section('/', 1, 1);
         QVariant  mytefsir=txtdata.toString().section('/', -1);
         open_dataBase(myname,action->text(),myaut,myid.toInt());
         m_isTefsir[m_currentBookIndex]=mytefsir.toBool();
     }
 }
